package com.yanqu.road.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 对Properties做简单的封装
 */
public class MyProperties {

	private final Logger logger = LogManager.getLogger(MyProperties.class);

	private Properties properties;

	public MyProperties(String filePath) {
		properties = loadProp(filePath);
	}

	public MyProperties() {

	}

	public String getProperty(String key) {
		return properties.getProperty(key);
	}

	public int getInt(String key, int defaultValue) {
		String value = properties.getProperty(key);
		if (StringUtils.isEmpty(value)) {
			return defaultValue;
		}
		return Integer.parseInt(value);

	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public String getProperty(String key, String defaultValue) {
		return properties.getProperty(key, defaultValue);
	}

	public double getDouble(String key) {
		String value = properties.getProperty(key);
		return Double.parseDouble(value);

	}


	public Properties getProperties() {
		return properties;
	}


	public long getLong(String key, long defaultValue) {
		String value = properties.getProperty(key);
		if (StringUtils.isEmpty(value)) {
			return defaultValue;
		}
		return Long.parseLong(value);

	}

	public Properties loadProp(String filePath) {
		if (StringUtils.isEmpty(filePath)) {
			throw new RuntimeException("Properties file path can't null");
		}
		Properties prop = new Properties();
		InputStream fileinputstream = null;
		try {
			fileinputstream = new FileInputStream(filePath);
			prop.load(fileinputstream);
			properties = prop;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				if (null != fileinputstream) {
					fileinputstream.close();
				}
			} catch (IOException e) {
				logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
				logger.info(" filePath：{}", filePath);
			}
		}
		return prop;
	}



	public int getInt(String key) {
		return Integer.parseInt(properties.getProperty(key));
	}

	public long getLong(String key) {
		return Long.parseLong(properties.getProperty(key));
	}

	public boolean getBoolean(String key, boolean defaultValue) {
		String value = properties.getProperty(key);
		if (StringUtils.isEmpty(value)) {
			return defaultValue;
		}
		return Boolean.parseBoolean(value);

	}

	public boolean getBoolean(String key) {
		return Boolean.parseBoolean(properties.getProperty(key));
	}

	public double getDouble(String key, double defaultValue) {
		String value = properties.getProperty(key);
		if (StringUtils.isEmpty(value)) {
			return defaultValue;
		}
		return Double.parseDouble(value);

	}



}
